package com.seven.resource;

import com.seven.domain.UserGroupInfo;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.assertj.core.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
@Slf4j
public class GroupInfoResource {

  private List<String> groupSet;

  private Map<String, List<UserGroupInfo>> groupUserMap;

  @Value("${invoice.user.path:group-info.csv}")
  private String groupInfoPath;

  @PostConstruct
  public void init(){
    List<UserGroupInfo> userGroupInfoList;
    try (Reader reader = Files.newBufferedReader(Paths.get(groupInfoPath))) {
      Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);
      userGroupInfoList = new ArrayList<>();
      UserGroupInfo userGroupInfo;
      for (CSVRecord record : records) {
        log.debug("Record #: {}", record.getRecordNumber());
        userGroupInfo = new UserGroupInfo();
        userGroupInfo.setUserName(record.get(0));
        userGroupInfo.setUserCode(record.get(1));
        userGroupInfo.setGroupName(record.get(2));
        userGroupInfoList.add(userGroupInfo);
      }
    } catch (IOException ex) {
      log.info("读取组织信息失败", ex);
      throw new RuntimeException("读取组织信息失败");
    }

    if (!CollectionUtils.isEmpty(userGroupInfoList)) {
      groupSet = userGroupInfoList.stream().map(UserGroupInfo::getGroupName).distinct()
          .collect(Collectors.toList());
      groupUserMap = new HashMap<>(groupSet.size());
      for (UserGroupInfo userGroupInfo : userGroupInfoList) {
        List<UserGroupInfo> userInfoSet = groupUserMap.get(userGroupInfo.getGroupName());
        if (Objects.isNull(userInfoSet)) {
          userInfoSet = new ArrayList<>();
          userInfoSet.add(userGroupInfo);
          groupUserMap.put(userGroupInfo.getGroupName(), userInfoSet);
        } else {
          userInfoSet.add(userGroupInfo);
        }
      }
    } else {
      log.warn("读取组织信息为空");
    }
  }

  public List<String> getGroupList() {
    return groupSet;
  }

  public List<UserGroupInfo> getGroupUserList(String groupName) {
    if (Strings.isNullOrEmpty(groupName)) {
      return null;
    }
    return groupUserMap.get(groupName);
  }

}
